import CryptoJS from 'crypto-js';

// 生成签名的函数    
//  params = { appKey,signMethod,v,timestamp: new Date().toISOString().slice(0, 19).replace('T', ''),};
function generateSignature(params, appSecret, signMethod) {
    // 对参数进行排序，忽略空值和 sign 参数
    const sortedParams = Object.entries(params)
       .filter(([key, value]) => key!== 'sign' && value!== null)
       .sort((a, b) => a[0].localeCompare(b[0]));

    // 拼接参数
    const dataToSign = sortedParams.map(pair => pair.join('')).join('');
    console.log('拼接是否正确'+ dataToSign);

    if (signMethod === 'md5') {
        const signStr = appSecret + dataToSign + appSecret;
        return CryptoJS.MD5(signStr).toString(CryptoJS.enc.Hex).toUpperCase();
    } else if (signMethod === 'hmac-sha256') {
        const hmac = CryptoJS.HmacSHA256(dataToSign, appSecret);
        return hmac.toString(CryptoJS.enc.Hex).toUpperCase();
    } else {
        throw new Error('Unsupported sign method');
    }
}

//发送网络请求
function sendRequest(url, appKey, appSecret, signMethod, v,testParams={}) {
    return new Promise((resolve, reject) => {
        const params = {
            appKey,
			signMethod,
            v,
			timestamp:formatTimestamp(),
           
            ...testParams
        };

        const sign = generateSignature(params, appSecret, signMethod);
	
		
        params.sign = sign;
       console.log("传入的参数"+JSON.stringify(url),JSON.stringify( params))
        wx.request({
            url,
            method: 'GET',
            data: params,
            header: {
               
                'Content-Type': 'application/x-www-form-urlencoded' 
            },
            success: res => {
                resolve(res.data);
            },
            fail: err => {
                reject(new Error(`Request failed: ${err.errMsg}`));
            }
        });
    });
}

function formatTimestamp() {
    // 创建一个 Date 对象，传入时间戳（需要注意的是，JavaScript 的 Date 构造函数接受的是毫秒级时间戳，如果传入的是秒级时间戳，需要乘以 1000）
    const date = new Date();

    // 处理 GMT+8 时区，确保时间正确
    const offset = date.getTimezoneOffset();
    const gmt8Date = new Date(date.getTime() + offset * 60 * 1000 + 8 * 60 * 60 * 1000);

    // 获取年、月、日、时、分、秒
    const year = gmt8Date.getFullYear();
    const month = String(gmt8Date.getMonth() + 1).padStart(2, '0');
    const day = String(gmt8Date.getDate()).padStart(2, '0');
    const hours = String(gmt8Date.getHours()).padStart(2, '0');
    const minutes = String(gmt8Date.getMinutes()).padStart(2, '0');
    const seconds = String(gmt8Date.getSeconds()).padStart(2, '0');

    // 按照 yyyy-MM-dd HH:mm:ss 的格式拼接字符串
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 导出默认函数，用于发起请求
export default async function wqblb(url, testParams) {
    const appKey = '850393088';
    const appSecret = "4a404fe62f052da8bffa70198c3dc859";
    const signMethod = 'hmac-sha256';
    const v = "0.1";
   
var    response=  await  sendRequest(url, appKey, appSecret, signMethod, v, testParams)
  return response
	
}



